import React, { useState, useEffect } from "react";
import { useDrag, useDrop } from "react-dnd";
import styles from "./index.less";
import { uuid, initData } from "./util";
import GridLayout, { WidthProvider } from "react-grid-layout";
import BasicLayout from "./container";
import DragLayout from "./DragLayout";
const ReactGridLayout = WidthProvider(GridLayout);
const canvasW = 375;
const canvasH = 667;
const componentList = [
  {
    type: "BOX",
    name: "red",
    bgColor: "red",
    h: 100,
    w: 375,
  },
  { type: "BOX", name: "blue", bgColor: "blue", h: 30, w: 375 },
  { type: "BOX", name: "yellow", bgColor: "yellow", h: 150, w: 375 },
];
let dataList = [];
for (let i = 0; i < 200; i++) {
  dataList.push(i);
}
function ShowList({ list }) {
  if (!list || !list.length) return null;
  return (
    <div>
      <div style={{ position: "relative" }}>
        <DragLayout
          // margin={[0, 0]}
          // verticalCompact={true}
          // cols={12}
          // rowHeight={2}
          // width={canvasW}

          data={list}
        >
          {list.map((item, index) => {
            return (
              <div key={item.id}>
                <Box item={item} isShow={true} index={index} />
              </div>
            );
          })}
        </DragLayout>
      </div>
    </div>
  );
}
function Box({ item, index, isShow, isLast }) {
  return (
    <div
      data-id={item?.id}
      className={styles.box}
      style={{
        backgroundColor: `${item?.bgColor}`,
        width: isShow ? `${item.w}px` : "50px",
        height: item.h,
      }}
    >
      <h3>
        {item?.name}
        {index}
      </h3>
    </div>
  );
}
function BoxDraw({ item, index, isShow, onRemove }) {
  return (
    <div className={styles.boxDraw}>
      <div onClick={onRemove} className={styles.removeBtn}>
        X
      </div>
      <Box item={item} isShow={isShow} index={index} />
    </div>
  );
}
function BoxDrag({ item }) {
  const [{ isDragging }, drag, dragPreview] = useDrag(() => ({
    type: item?.type,
    item: item,
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  return (
    <div ref={dragPreview} style={{ opacity: isDragging ? 0.5 : 1 }}>
      <div role="Handle" ref={drag}>
        <Box item={item} />
      </div>
    </div>
  );
}
function Bucket({
  onDrop,
  list,
  onDragStop,
  onDragStart,
  onResizeStop,
  onRemove,
  onLayoutChange,
  onChange,
}) {
  const _onDrop = (item, monitor, onChange) => {
    if (monitor.isOver()) {
      onDrop && onDrop(item);
    }
  };
  const [collected, drop] = useDrop(
    () => ({
      accept: "BOX",
      drop: _onDrop,
      collect: (monitor, props) => {
        return {
          isOver: monitor.isOver(),
          canDrop: monitor.canDrop(),
          getItem: monitor.getItem(),
        };
      },
    }),
    [onDrop, list]
  );
  const _onDragStop = (layout, oldItem, newItem, placeholder, e, element) => {
    onDragStop && onDragStop(newItem);
  };
  const _onResizeStop = (layout, oldItem, newItem, placeholder, e, element) => {
    onResizeStop && onResizeStop(newItem);
  };
  const _onDragStart = (layout, oldItem, newItem, placeholder, e, element) => {
    onDragStart && onDragStart(newItem);
  };
  const getLoyout = () => {
    if (!list || list.length <= 0) {
      return [];
    }
    let m = [];
    list.map((item, index) => {
      m.push(item.point);
    });
    return m;
  };

  return (
    <div>
      <h1>编辑界面</h1>
      <div
        ref={drop}
        role={"Dustbin"}
        style={{
          width: `${canvasW}px`,
          height: `${canvasH}px`,
          position: "relative",
        }}
      >
        <DragLayout onChange={onChange} data={list}>
          {list.map((item, index) => {
            return (
              <BoxDraw
                key={item.id}
                onRemove={() => onRemove(item, index)}
                isShow={true}
                item={item}
                index={index}
              />
            );
          })}
        </DragLayout>
      </div>
    </div>
  );
}

function Index({ srcId }) {
  const [list, setList] = useState([]);
  const [isShowPage, setShowPage] = useState(false);
  // cols={12}
  // rowHeight={2}
  const getAllH = () => {
    let allH;
    list.forEach((item) => {
      allH += item.h;
    });
    if (allH) return allH;
    return 0;
  };
  const onAdd = (item) => {
    let _item = {
      ...item,
      id: uuid(),
      point: {},
      draggable: true,
    };

    const allH = getAllH();

    const index = list.push(_item);

    list[index - 1]["point"] = {
      id: _item.id,
      x: 0,
      y: allH,
      w: ((_item.w / canvasW) * canvasW) / 12,
      h: ((item.h / canvasH) * canvasH) / 2,
      // isDraggable: true,
      // isResizable: true,
      // static: index == 3 ? true : false,
    };
    setList([...list]);
  };
  const onChange = (data) => {
    setList([...data]);
  };
  const _onDragStop = (newItem) => {
    const index = list.findIndex((item) => item.id === newItem.i);
    list[index] = { ...list[index], point: newItem };
    setList([...list]);
  };

  const _onResizeStop = (newItem) => {
    const index = list.findIndex((item) => item.id === newItem.i);
    list[index] = { ...list[index], point: newItem };
    setList([...list]);
  };

  const _onDragStart = (newItem) => {
    console.log("_onDragStart", newItem);
    const index = list.findIndex((item) => item.id === newItem.i);
    list[index] = { ...list[index], point: newItem };
    setList([...list]);
  };
  const onRemove = (item) => {
    const index = list.findIndex((sitem) => sitem.id === item.id);
    list.splice(index, 1);

    setList([...list]);
  };
  const showPage = () => {
    setShowPage(!isShowPage);
  };
  console.log(JSON.stringify(list));
  return (
    <div className={styles.index}>
      <div className={styles.componentList}>
        {componentList.map((item, index) => {
          return <BoxDrag item={item} key={item?.name} />;
        })}
      </div>

      <Bucket
        onRemove={onRemove}
        onDragStop={_onDragStop}
        onDragStart={_onDragStart}
        onResizeStop={_onResizeStop}
        list={list}
        onDrop={onAdd}
        onChange={onChange}
      />
      <div className={styles.show}>
        <h1 onClick={showPage}>预览</h1>
        {isShowPage ? (
          <ShowList
            key={uuid()}
            list={[
              {
                type: "BOX",
                name: "yellow",
                bgColor: "yellow",
                h: 150,
                w: 375,
                id: "fc7e833e-7bd5-2ed8-1440-e7d7fd23739e",
                point: {
                  w: 12,
                  h: 75,
                  x: 0,
                  y: 86,
                  i: "fc7e833e-7bd5-2ed8-1440-e7d7fd23739e",
                  moved: true,
                  static: false,
                },
              },
              {
                type: "BOX",
                name: "red",
                bgColor: "red",
                h: 100,
                w: 375,
                id: "0c9c6749-0729-e54f-6736-93ab76c760c9",
                point: {
                  w: 12,
                  h: 50,
                  x: 0,
                  y: 187,
                  i: "0c9c6749-0729-e54f-6736-93ab76c760c9",
                  moved: true,
                  static: false,
                },
              },
              {
                type: "BOX",
                name: "blue",
                bgColor: "blue",
                h: 30,
                w: 375,
                id: "4d2f363a-a2f2-d28f-561f-f8f701841b96",
                point: {
                  w: 12,
                  h: 15,
                  x: 0,
                  y: 0,
                  i: "4d2f363a-a2f2-d28f-561f-f8f701841b96",
                  moved: false,
                  static: false,
                },
              },
            ]}
          />
        ) : null}
      </div>
    </div>
  );
}

export default Index;
